package com.zh.yida.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class})
@ResponseBody
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException se) {
        log.error(se.getMessage());
        String[] split = se.getMessage().split(" ");
        if (se.getMessage().contains("Duplicate entry")) {
            return R.error("名称" + split[2] + " 太火爆了，请换一个");
        }
        return R.error("该名称太火爆了，请换一个");
    }

    /**
     * 拦截自定义异常并返回错误信息
     * @param be
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R<String> businessException(BusinessException be) {
        return R.error(be.getMessage());
    }
}
